/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p>
 * Compile: JDK 1.6+
 * <p>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p>
 * 公司名称：江苏欧索软件有限公司
 * <p>
 * 公司地址：中国苏州科技城青山路1号
 * <p>
 * 网址: http://www.oceansoft.com.cn
 * <p>
 * 作者: 090922(陈伟)
 * <p>
 * 文件名: com.oceansoft.mobile.econsole.interceptor.SpringSessionInterceptor.java 
 * <p>
 * 类产生时间: 2014/4/27 0027 下午 23:45
 * <p>
 * 负责人: 090922(陈伟)
 * <p>
 * Email:javacspring@gmail.com
 * <p>
 * 所在组 : 掌上公安应用平台
 * <p>
 * 所在部门: 开发部--手持技术部
 * <p>
 * <p>
 */
package com.oceansoft.mobile.econsole.interceptor;

import com.oceansoft.mobile.econsole.common.util.ServerInfo;
import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

import static com.oceansoft.mobile.econsole.common.constant.Constant.SESSION_USER;

/**
 * 会话拦截器
 *
 * @author: chenw
 * @time: 2014/4/27 0027 下午 23:45
 */
public class SpringSessionInterceptor implements HandlerInterceptor {

    private final Logger opeLog = Logger.getLogger("oper");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long _start = System.currentTimeMillis();
        String requestUrl = request.getRequestURI().toLowerCase();
        boolean isAjax = ServerInfo.isAjax(request);
        //        sessionObj = null;
        boolean isLogin = (request.getSession().getAttribute(SESSION_USER) != null);
        boolean isSafeUrl = requestUrl.matches("(/\\w*|/)/(profile/(login|auth|re-login|logout))(;jsessionid=.*)?");
        request.setAttribute("START_REQUEST", _start);
        System.out.print(String.format("RequestStart:=====>%d Access URL=>%s", _start, requestUrl));
        if (isSafeUrl) {
            return true;
        }
        //非安全URL
        if (isLogin) {//登录用户
            HandlerMethod method = (HandlerMethod) handler;
          boolean hasPrivilege = hasPrivilege(request.getSession(), String.format("%1$s#%2$s", method.getBean().getClass().getName(), method.getMethod().getName()));
        
            if (hasPrivilege) {
                return true;
            } else {
                System.out.println(String.format("\n\n权限不足:====>%1$s#%2$s\n\n", method.getBean().getClass().getName(), method.getMethod().getName()));
                if (isAjax) {
                    PrintWriter out = response.getWriter();
                    out.println(new String("{\"statusCode\":\"403\", \"message\":\"访问受限，请与管理员联系!\"}".getBytes("UTF-8"), "ISO8859-1"));
                    out.flush();
                    out.close();
                    return false;
                } else {
                    request.getRequestDispatcher("/WEB-INF/views/errors/403.jsp").forward(request, response);
                    return true;
                }
            }
        } else {//非登录用户
            if (isAjax) {
                PrintWriter out = response.getWriter();
                out.println(new String("{\"statusCode\":\"301\", \"message\":\"会话超时，请重新登录!\"}".getBytes("UTF-8"), "ISO8859-1"));
                out.flush();
                out.close();
                return false;
            } else {
                response.sendRedirect(request.getContextPath());
                return true;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        long _end = System.currentTimeMillis();
        System.out.print(String.format("\nRequestEnd:=====>%d，共计耗时:%s毫秒\n\n", _end, (_end - Long.valueOf(request.getAttribute("START_REQUEST").toString()))));
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        //记录系统日志
        /*SysUser user = (SysUser) request.getSession().getAttribute(SESSION_USER);
        if (null == user)
            return;
        Object log_content = request.getAttribute(OPERATION_LOG_CONTENT);
        MDC.put("ip", request.getRemoteHost());
        MDC.put("userId", user.getId());
        MDC.put("userName", user.getRealName());
        if (log_content != null) {
            opeLog.info(log_content);
        } else if (Constant.RECORD_DEFAULT_OPERATION_LOG) {
            opeLog.info(o.toString());
        }*/
    }

    /**
     * 判断当前用户是否有权限执行此操作
     *
     * @param session 当前登录用户会话信息
     * @param path    访问资源路径
     * @return true有权限 false无权限
     */
    private boolean hasPrivilege(HttpSession session, String path) {
        /*if (null != path && 0 < path.length()) {
            Set<String> pris = (Set<String>) session.getAttribute(SESSION_USER_PRIVILEGE);
            return pris.contains(path);
        }
        return false;*/
        return true;
    }
}
